package com.neo.tiny.search.es.controller.es;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neo.tiny.common.common.ResResult;
import com.neo.tiny.resolver.CommonPage;
import com.neo.tiny.search.api.vo.db.EsPreServiceResVO;
import com.neo.tiny.search.es.domain.es.EsSearchPre;
import com.neo.tiny.search.es.service.EsPreService;
import com.neo.tiny.search.api.vo.es.HighLightSearchReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Collection;

/**
 * @Description: 搜索管理
 * @Author: yqz
 * @CreateDate: 2022/10/20 23:20
 */
@Api(tags = "ES搜索管理", description = "ES搜索管理")
@RestController
@RequestMapping("/es/search")
public class EsSearchController {

    @Autowired
    private EsPreService esPreService;

    @ApiOperation(value = "导入数据库中所有数据到ES")
    @PostMapping("/import-from-mysql")
    public ResResult<Integer> importData() {

        int count = esPreService.importAllData();
        return ResResult.success(count);

    }

    @ApiOperation(value = "简单搜索")
    @GetMapping("/simple-search")
    public ResResult<IPage<EsPreServiceResVO>> simpleSearch(@RequestParam(required = false) String keyword,
                                                            @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                                                            @RequestParam(required = false, defaultValue = "20") Integer pageSize) {

        Page<EsSearchPre> searchRes = esPreService.search(keyword, pageNum, pageSize);
        IPage<EsPreServiceResVO> page = CommonPage.restPage(searchRes, EsPreServiceResVO.class);

        return ResResult.success(page);
    }

    @ApiOperation(value = "高亮搜索")
    @GetMapping("/higLight-search")
    public ResResult<IPage<EsPreServiceResVO>> highLightSearch(HighLightSearchReqVO req) {

        Page<EsSearchPre> esSearchPres = esPreService.highLightSearch(req.getKeyword(), req.getCurrent(), req.getSize());

        return ResResult.success(CommonPage.restPage(esSearchPres, EsPreServiceResVO.class));
    }


    @ApiOperation("删除索引")
    @DeleteMapping("/del-index")
    public ResResult<Boolean> deleteIndex(@RequestParam(name = "index", required = true) String index) throws IOException {
        return ResResult.success(esPreService.delIndex(index));
    }

    @ApiOperation("获取所有索引")
    @GetMapping("/list-index")
    public ResResult<Collection<String>> listAllIndex() throws IOException {

        return ResResult.success(esPreService.listAllIndex());
    }
}
